<?php
/**
 * Administracja - generowanie plików i zatwierdzanie niemożliwości
 * @author Miron Pawlik
 */

if($user->isAdmin()) {
    //sprawdzanie czy sa jakies 'niemozliwe' terminy do zaakceptowania

    if(isset($fd['accept'])){
        $additionalCond = ' AND indexID = '.$fd['indexID'];
    }
    else{
        $additionalCond = '';
    }
    if($someStudent = $db->getAll('studentTerms', 'RANDOM()', 'weight = -1 AND acceptReason is null '.$additionalCond, 1, 'indexID'))
    {
        
        
        $q = $db->query("SELECT s.name as name, s.surname as surname, st.indexID as indexID, st.subjectID as subjectID, st.termGenId as termGenId, st.reason as reason, sub.name as subname, t.day as day, t.week as week, t.timeStart as timeStart, t.timeEnd as timeEnd, t.teacher as teacher
					 FROM studentTerms as st JOIN students as s ON s.indexId = st.indexId JOIN subjects as sub ON sub.subjectID = st.subjectID JOIN terms as t ON t.subjectID = st.subjectID AND t.genID = st.termGenId WHERE st.weight == -1 AND st.acceptReason is null AND st.indexID = '".$someStudent[0]['indexID']."' ORDER BY st.indexId, st.subjectId");
        $acc = $q->fetchAll();
        $smarty->assign('accept', $acc);
        $smarty->assign('adminTpl', 'admin/accept.tpl');
        $smarty->assign('week', $weeks);
        $smarty->assign('days', $days);
        $smarty->assign('hours', $hours);
        if($fd->issetParam('accept')) {
            $query = $db->prepare("UPDATE studentTerms SET `weight` = :we, `acceptReason` = :acc WHERE `indexID` = :index AND subjectID = :subject AND termGenID = :term");
            foreach($acc as $a) {
                $query->bindValue(':index', $a['indexID']);
                $query->bindValue(':subject', $a['subjectID']);
                $query->bindValue(':term', $a['termGenId']);

                if($fd['acc'][$a['indexID']][$a['subjectID']][$a['termGenId']]) {
                    $query->bindValue(':acc', 1);
                    $query->bindValue(':we', -1);
                }
                else {
                    $query->bindValue(':acc', 0);
                    $query->bindValue(':we', 0);
                }
                $query->execute();
            }
            
            header("Location: ".$_conf['host'].'?admin,generate');
        }
    }

    if($fd[2] == "prefs") {
        //generowanie preferencji
        $preferences = $db->getAll('studentTerms', 'indexId, subjectId');
        $lastIndexNr = 0;
        $lastSubjectId = 0;
        $buff = "";
        //listowanie wszsystkich rekordow
        foreach($preferences as $pref) {
            //sprawdzanie czy aktualny rekord wciaz nalezy do tego samego studenta
            if($lastIndexNr != $pref['indexID']) {
                //jesli nie, to dajemy naglowek z id nowego studenta

                $buff .= "\n[".$pref['indexID'].']';
            }
            //sprawdzanie czy akutalny rekord to przypadkiem nie nowy przedmiot
            if($lastSubjectId != $pref['subjectID'] || $lastIndexNr != $pref['indexID']) {
                $lastSubjectId = $pref['subjectID'];
                $buff .= "\n".$pref['subjectID'].':';
            }
            $lastIndexNr = $pref['indexID'];
            //wypisywanie terminu, oraz wagi (waga ujemna, to brak mozliwosci uczeszczania na dany termin)
            if($pref['weight'] != -1)
                $buff .= $pref['termGenId'].','.($_conf['ptsPerSub'] - ($pref['weight']==0?(-1*$_conf['ptsAll']):$pref['weight'])).';';
        }
        //wysylanie odpowiednich naglowkow i tresci pliku
        header('Content-type: text/plain');
        header('Content-Disposition: attachment; filename="prefs.txt"');
        die($buff);
    }
    if($fd[2] == "terms") {
        $buff = "";

        //genreowanie przedmiotow
        $subjects = $db->getAll('terms', 'subjectId, genId');
        $lastSubjectId = 0;
        foreach($subjects as $sub) {
            if($lastSubjectId != $sub['subjectID']) {
                //jesli nie, to dajemy naglowek z id nowego przedmiotu
                $lastSubjectId = $sub['subjectID'];
                $buff .= "\n[".$sub['subjectID'].']';
            }
            $buff .= "\n".$sub['genID'].':'.$sub['capacity'].':'.$sub['day'].':'.$sub['timeStart'].':'.$sub['timeEnd'];

        }
        $buff .= "\n[kolizje]\n";
        //genenerowanie kolizji (osobno dla kazdego dnia tygodnia A i B)
        for($i=0; $i<14; $i++) {
            $terms = $db->getAll('terms', 'timeStart', 'day = '.(int)($i/2) . ' AND (week == 0 OR week == '.($i%2+1).')');
            $size = count($terms);
            $lastKey = 0;
            //bierzemy po koleji wszystkie terminy
            foreach($terms as $key => $t) {
                $j = $key+1;
                //sprawdzamy nestepne terminy, czy nie pokrywaja sie z obecnym
                while($j < $size) {
                    if($t['timeEnd'] > $terms[$j]['timeStart']) {
                        $buff .= $t['subjectID'].','.$t['genID'].';';
                        $buff .= $terms[$j]['subjectID'].','.$terms[$j]['genID']."\n";
                    }
                    $j++;
                }
            }

        }
        //wysylanie naglowkow i tresci pliku
        header('Content-type: text/plain');
        header('Content-Disposition: attachment; filename="terms.txt"');
        die($buff);
    }
    if($fd[2] == 'groups') {
        $query = $db->query("SELECT * FROM groups AS g LEFT JOIN students AS s ON g.ownerID = s.indexID LEFT JOIN students AS ss ON g.memberID = ss.indexID WHERE s.register = 1 AND ss.register = 1 ORDER BY subjectID, ownerID");
        $buffer = $query->fetchAll();
        $lastOwner = 0;
        $lastSubject = 0;

        foreach($buffer as $line) {
            if($line['ownerID'] == $lastOwner && $line['subjectID'] == $lastSubject) {
                $buff .= ",".$line['memberID'];
            }
            else {
                $buff .= "\n".$line['subjectID'].':'.$line['memberID'];
                $lastOwner = $line['ownerID'];
                $lastSubject = $line['subjectID'];
            }
        }
        header('Content-type: text/plain');
        header('Content-Disposition: attachment; filename="groups.txt"');
        die($buff);

    }
}
